import {defineStore,acceptHMRUpdate} from 'pinia'
import {ref} from 'vue'
import { asyncRoutes } from '@/router'
import {RouteRecordRaw} from 'vue-router'

/**
 * 当前登录用户信息
 */
export const useUserStore = defineStore('userStore', ()=>{
    const name = ref('')
    const staffId = ref('')
    const theUser = ref<IUserInfo|null>(null)

    function login(loginUser?:IUserInfo){
        if(loginUser){
            name.value = loginUser.name;
            staffId.value =  loginUser.staffId;
            theUser.value = loginUser;
        }
        
    }

    return {
        name,staffId,login,theUser
    }

});

//保存当期用户授权的路由信息，后续根据此生成菜单、添加动态路由
export const useRouteStore = defineStore('useRoute',()=>{

    let accessedRoutes = ref<RouteRecordRaw[]>([]);


    //根据权限生成路由
    
    function generateRouteByPers(perms:string[]){

        if (perms.includes('*')) {
            accessedRoutes.value = asyncRoutes;
        } else {
            accessedRoutes.value = filterAsyncRoutes(asyncRoutes, perms)
        }

        //初始化小红点
        

        console.log('generateRouteByPers')
        console.log(accessedRoutes);
    }

    function hasPermission(perms:string[], route:RouteRecordRaw) {

        console.log('has permis:')
        console.log(route.meta?.perms)

        let has = false;
        perms.forEach((p)=>{
          if(route.meta && route.meta.perms && p != null){
            var menuPerms = route.meta.perms;

            //@ts-ignore
            menuPerms.forEach((menuPerm)=>{
              if(menuPerm.toLowerCase() == p.toLocaleLowerCase()) {
                has = true;
              }
            });

          }
        });
        return has;

        /*

        if (route.meta && route.meta.perms) {
          return perms.some(perm => route.meta?.perms?.includes(perm))
        } else {
          return true
        }
          */
      }

    function filterAsyncRoutes(routes:RouteRecordRaw[], perms:string[]) {
        const res:RouteRecordRaw[] = [];
      
      console.log('filter route')
      console.log(routes)

        routes.forEach(route => {
          const tmp = { ...route }
          if (tmp.children) {
            tmp.children = filterAsyncRoutes(tmp.children, perms)
            if (tmp.children && tmp.children.length > 0) {
              res.push(tmp)
            }
          } else {
            if (hasPermission(perms, tmp)) {
              res.push(tmp)
            }
          }
        })
        return res
    }

      return {
        accessedRoutes,
        generateRouteByPers
      }
});

if(import.meta.hot){
    import.meta.hot.accept(acceptHMRUpdate(useUserStore,import.meta.hot));
}